<body>
    <h1></h1>
    <button class="btn-run">run</button>
</body>
<script>
    const el = document.querySelector('h1')

    function jsonp(url, params = {}) {
        return new Promise((resolve, reject) => {
            const baseURL = 'http://localhost:2333'
            const script = document.createElement('script')
            const cbKey = `__jsonp_${Math.random().toString().substr(2, 8)}`
            window[cbKey] = (response) => {
                Reflect.deleteProperty(window, cbKey)
                script.remove()
                return resolve(response)
            }
            script.id = cbKey
            script.src = `${baseURL}/${url}?callback=${cbKey}&&params=${JSON.stringify(params)}`
            script.onerror = reject
            document.body.appendChild(script)
        })
    }

    document.querySelector('.btn-run').onclick = () => {
        el.innerText = '加载中...'
        jsonp('', { age: 20 })
            .then(res => {
                el.innerText = res.username + ' ' + res.age
            })
            .catch(() => {
                el.innerText = '请求失败！'
            })
    }
</script>
